#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common.h"
#include "base64.h"
#include "my_errno.h"

#define ENCODE_SIZE 3*512
#define DECODE_SIZE 4*512

int main(int argc, char *argv[])
{
	if(argc != 4)
	{
		DEBUG("命令行输入模式: ./target (-e or -d) AAA BBB\n");
		return ERR_INVALID_INPUT;
	}
	FILE *fp_read = NULL;
	FILE *fp_write = NULL;
	int n, m;
	char encode_buffer[ENCODE_SIZE] = {0};
	char decode_buffer[DECODE_SIZE] = {0};

	fp_read = fopen(argv[2],"r");
	fp_write = fopen(argv[3],"w+");

	ASSERT(fp_read);
	ASSERT(fp_write);

	if(strcmp(argv[1],"-e")==0)
	{
		n = fread(encode_buffer,1,ENCODE_SIZE,fp_read);
		while(n != 0)
		{
			m = base64Encode(decode_buffer, encode_buffer, n);
			if(m > 0)
			{
				DEBUG("read n = %d, encode m = %d\n", n, m);
				fwrite(decode_buffer, 1, m, fp_write);
				n = fread(encode_buffer,1,ENCODE_SIZE,fp_read);
			}
			else
			{
				DEBUG("encode error n = %d, m = %d\n", n, m);
				break;
			}
		}
		DEBUG("encode finish\n");
	}
	else if(strcmp(argv[1],"-d")==0)
	{
		n = fread(decode_buffer, 1, DECODE_SIZE, fp_read);
		while(n != 0)
		{
			m = base64Decode(encode_buffer, decode_buffer, n);
			if(m > 0)
			{
				DEBUG("read n = %d, decode m = %d\n", n, m);
				fwrite(encode_buffer, 1, m, fp_write);
				n = fread(decode_buffer, 1, DECODE_SIZE, fp_read);
			}
			else
			{
				DEBUG("decode error n = %d, m = %d\n", n, m);
				break;
			}
		}
		DEBUG("decode finish\n");
	}
	else
	{
		DEBUG("argv[1] error\n");
	}
	SAFECLOSE(fp_read);
	SAFECLOSE(fp_write);
	return 0;
}

